using System;
using LiteNetLib.Utils;

namespace LiteNetLib
{
	internal sealed class NetConnectRequestPacket
	{
		public const int HeaderSize = 13;

		public readonly long ConnectionTime;

		public readonly byte ConnectionNumber;

		public readonly NetDataReader Data;

		private NetConnectRequestPacket(long connectionId, byte connectionNumber, NetDataReader data)
		{
			ConnectionTime = connectionId;
			ConnectionNumber = connectionNumber;
			Data = data;
		}

		public static int GetProtocolId(NetPacket packet)
		{
			return BitConverter.ToInt32(packet.RawData, 1);
		}

		public static NetConnectRequestPacket FromData(NetPacket packet)
		{
			if (packet.ConnectionNumber >= 4)
			{
				return null;
			}
			long connectionId = BitConverter.ToInt64(packet.RawData, 5);
			NetDataReader netDataReader = new NetDataReader(null, 0, 0);
			if (packet.Size > 13)
			{
				netDataReader.SetSource(packet.RawData, 13, packet.Size);
			}
			return new NetConnectRequestPacket(connectionId, packet.ConnectionNumber, netDataReader);
		}

		public static NetPacket Make(NetDataWriter connectData, long connectId)
		{
			NetPacket netPacket = new NetPacket(PacketProperty.ConnectRequest, connectData.Length);
			FastBitConverter.GetBytes(netPacket.RawData, 1, 7);
			FastBitConverter.GetBytes(netPacket.RawData, 5, connectId);
			Buffer.BlockCopy(connectData.Data, 0, netPacket.RawData, 13, connectData.Length);
			return netPacket;
		}
	}
}
